package elitech.vietnam.weatherfashion.tabs.settings;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.weatherfashion.MainActivity;
import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.service.ImageUploader;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;

public class EditProfileFragment extends Fragment implements OnClickListener {

	private static final String MEMBER_FOLDER = "member_image/";
	public static EditProfileFragment THIS;

	private Button btnEditAvatar;
	private Button btnSave;
	private EditText edtStatus;
	private EditText edtName;
	private TextView tvSoKiTu;
	private TextView tvSoKiTuName;
	private ImageView imageViewAvatar;

	private int soKitu = 0;
	private int soKituName = 0;
	private final int SO_KI_TU_MAX = 60;
	private final int SO_KI_TU_MAX_NAME = 30;
	private ProgressDialog mProgressDialog;
	private Uri selectedImageUri;
	private MemberDTO user;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_edit_profile, null);
		user = GlobalValue.getInstance(getActivity()).readUserInfo();
		initView(view);
		THIS = this;
		return view;
	}

	private void initView(View view) {
		/*************************************/
		// hide keyboard
		try {
			InputMethodManager inputManager = (InputMethodManager) getActivity()
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			inputManager.hideSoftInputFromWindow(getActivity()
					.getCurrentFocus().getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
		} catch (Exception e) {
		}

		/************************************/
		Button btnBack = (Button) view.findViewById(R.id.btnBack);
		btnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// getFragmentManager()
				// .beginTransaction()
				// .replace(R.id.container_framelayout,
				// new SettingsFragment()).commit();
				getActivity().onBackPressed();
			}
		});

		/***********************************/
		btnEditAvatar = (Button) view.findViewById(R.id.btnEditAvatar);
		btnEditAvatar.setOnClickListener(this);
		/***********************************/
		btnSave = (Button) view.findViewById(R.id.btnSave);
		btnSave.setOnClickListener(this);

		/************************************/
		imageViewAvatar = (ImageView) view.findViewById(R.id.imageViewAvatar);

		if (user.getMemberPic() == null || user.getMemberPic().equals("")) {
			imageViewAvatar.setImageResource(R.drawable.no_avatar);
		} else {
			String imageUrl = Const.SERVER_IMAGE_URL
					+ user.getMemberPic();
			UrlImageViewHelper.setUrlDrawable(imageViewAvatar, imageUrl);
		}

		/*********************************/
		tvSoKiTu = (TextView) view.findViewById(R.id.tvSoKiTu);
		tvSoKiTuName = (TextView) view.findViewById(R.id.tvSoKiTuName);

		/**********************************/
		edtStatus = (EditText) view.findViewById(R.id.edtStatus);
		edtStatus.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

				soKitu = edtStatus.getText().length();
				tvSoKiTu.setText(soKitu + "/" + SO_KI_TU_MAX);

				if (s.toString().equals(user.getMemberProfile()))
					btnSave.setEnabled(false);
				else
					btnSave.setEnabled(true);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		edtStatus.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER) {

					int soLanEnter = edtStatus.getText().toString().length()
							- edtStatus.getText().toString().replace("\n", "")
									.length();
					Utils.Log(edtStatus.getText().toString()
							+ " - So lan enter " + soLanEnter);
					if (soLanEnter < 2) {
						return false;
					} else {
						return true;
					}
				}

				return false;
			}
		});
		edtStatus.setText(user.getMemberProfile());
		edtStatus.setSelection(soKitu);
		edtStatus.clearFocus();

		/**********************************/
		edtName = (EditText) view.findViewById(R.id.edtName);
		edtName.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

				soKituName = edtName.getText().length();
				tvSoKiTuName.setText(soKituName + "/" + SO_KI_TU_MAX_NAME);

				if (s.toString().equals(user.getMemberName()))
					btnSave.setEnabled(false);
				else
					btnSave.setEnabled(true);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		edtName.setText(user.getMemberName());
		edtName.setSelection(soKituName);
		edtName.clearFocus();

		/**************************/
		mProgressDialog = new ProgressDialog(getActivity());
		mProgressDialog.setTitle(getResources().getString(
				R.string.setting_edit_profile_progress_update_profile_title));
		mProgressDialog.setMessage(getResources().getString(
				R.string.setting_change_password_processing));
		mProgressDialog.setCancelable(false);
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

		switch (arg0.getId()) {
		case R.id.btnSave:
			if (checkDataInput()) {
				UpdateProfileAsynTask updateProfileAsynTask = new UpdateProfileAsynTask();
				updateProfileAsynTask.execute();
			}

			break;
		case R.id.btnEditAvatar:

			new PicPickerEditProfileDialog(getActivity(), this).show();

			break;
		default:
			break;
		}
	}

	private boolean checkDataInput() {
		if (edtName.getText().toString().equals("")) {
			showToast("Tên hiển thị không được để trống");
			return false;
		}
		return true;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		int n = requestCode & 0xffff;
		switch (n) {
		case MainActivity.REQ_CODE_EDIT_PROFILE_ALBUM:
			if (data != null) {
				try {
					selectedImageUri = data.getData();
					String fileName = user.getId() + "_"
							+ System.currentTimeMillis() + ".jpg";

					String photoPath = getPath(selectedImageUri);

					Bitmap bitmap;

					bitmap = MediaStore.Images.Media.getBitmap(getActivity()
							.getContentResolver(), selectedImageUri);

					// rote bitmap
					Bitmap roteBitmap = null;
					ExifInterface ei = new ExifInterface(photoPath);
					int orientation = ei.getAttributeInt(
							ExifInterface.TAG_ORIENTATION,
							ExifInterface.ORIENTATION_NORMAL);

					switch (orientation) {
					case ExifInterface.ORIENTATION_ROTATE_90:
						roteBitmap = rotateAndResizeImage(bitmap, 90);
						break;
					case ExifInterface.ORIENTATION_ROTATE_180:
						roteBitmap = rotateAndResizeImage(bitmap, 180);
						break;
					case ExifInterface.ORIENTATION_ROTATE_270:
						roteBitmap = rotateAndResizeImage(bitmap, 270);
						break;
					// etc.
					}

					Utils.Log("Start resize");

					// save to file
					if (roteBitmap == null) {
						roteBitmap = rotateAndResizeImage(bitmap, 0);
					}
					photoPath = Environment.getExternalStorageDirectory()
							+ "/_camera_avatar.jpg";
					writeTempBimap(roteBitmap, photoPath);

					Utils.Log("Stop resize");
					// Resize bitmap

					UpdateAvatarAsyntask updateAvataAsyntask = new UpdateAvatarAsyntask();
					updateAvataAsyntask.execute(photoPath, fileName);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			}
		case MainActivity.REQ_CODE_EDIT_PROFILE_CAMERA:

			try {
				Bitmap bmp = (Bitmap) data.getExtras().get("data");
				if (bmp.getHeight() > 200 || bmp.getWidth() > 200)
					bmp = rotateAndResizeImage(bmp, 0);

				String filePath = Environment.getExternalStorageDirectory()
						+ "/_camera_avatar.jpg";
				writeTempBimap(bmp, filePath);

				String fileName = user.getMemberUsername() + "_"
						+ System.currentTimeMillis() + ".jpg";

				UpdateAvatarAsyntask updateAvataAsyntask = new UpdateAvatarAsyntask();
				updateAvataAsyntask.execute(filePath, fileName);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		}
	}

	private Bitmap rotateAndResizeImage(Bitmap bitmap, float angle) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float scaleWidth = ((float) 200) / width;
		float scaleHeight = ((float) 200) / height;

		Matrix matrix = new Matrix();
		matrix.postRotate(angle, scaleWidth, scaleHeight);
		Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
		return Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(),
				scaledBitmap.getHeight(), matrix, true);
	}

	private void writeTempBimap(Bitmap bitmap, String filePath) {
		try {
			ByteArrayOutputStream stream = new ByteArrayOutputStream();

			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
			byte[] byteArray = stream.toByteArray();

			// save it in your external storage.
			FileOutputStream fo;

			fo = new FileOutputStream(new File(filePath));
			fo.write(byteArray);
			fo.flush();
			fo.close();
		} catch (Exception e) {
		}

	}

	/**
	 * helper to retrieve the path of an image URI
	 */
	@SuppressWarnings("deprecation")
	public String getPath(Uri uri) {
		// just some safety built in
		if (uri == null) {
			// TODO perform some logging or show user feedback
			return "";
		}
		// try to retrieve the image from the media store first
		// this will only work for images selected from gallery
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = getActivity().managedQuery(uri, projection, null, null,
				null);
		if (cursor != null) {
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		}
		// this is our fallback here
		return uri.getPath();
	}

	private void showToast(String mess) {
		Toast.makeText(getActivity(), mess, Toast.LENGTH_SHORT).show();
	}

	private class UpdateProfileAsynTask extends
			AsyncTask<String, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {

			PHPSoapServiceCaller service = new PHPSoapServiceCaller();
			MemberDTO member = user;
			// boolean response = service.updateProfileMember(
			// member.getMemberUsername(), member.getMemberPassword(),
			// edtStatus.getText().toString());

			boolean response = false;
			try {
				response = service.updateNameProfileMember(member
						.getMemberUsername(), member.getMemberPassword(),
						edtName.getText().toString(), edtStatus.getText()
								.toString());
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (response) {
				user.setMemberProfile(edtStatus.getText().toString());
				user.setMemberName(edtName.getText().toString());
				GlobalValue.getInstance(getActivity()).writeUserInfo(user);
			}

			return response;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			mProgressDialog.dismiss();
			if (result) {

				// hide keyboard
				InputMethodManager inputManager = (InputMethodManager) getActivity()
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				inputManager.hideSoftInputFromWindow(getActivity()
						.getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
				//

				showToast(getResources().getString(
						R.string.setting_edit_profile_success));

				btnSave.setEnabled(false);
			} else {
				showToast(getResources().getString(
						R.string.setting_edit_profile_fail));
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			mProgressDialog.show();
		}
	}

	class UpdateAvatarAsyntask extends AsyncTask<String, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {

			final String filePath = params[0];
			String fileName = params[1];
			String mem_pic = MEMBER_FOLDER + fileName;

			ImageUploader imageUploader = new ImageUploader();

			boolean uploadOk = false;
			uploadOk = imageUploader.upload(filePath, fileName);

			if (uploadOk) {
				// user.setMemberPic(fileName);
				PHPSoapServiceCaller service = new PHPSoapServiceCaller();

				try {
					uploadOk = service.updateImageMember(
							user.getMemberUsername(), user.getMemberPassword(),
							mem_pic);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (uploadOk) {

				user.setMemberPic(mem_pic);
				GlobalValue.getInstance(getActivity()).writeUserInfo(user);
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// imageViewAvatar.setImageURI(null);
						// imageViewAvatar.setImageURI(Uri.fromFile(new File(
						// filePath)));

						String imageUrl = Const.SERVER_IMAGE_URL
								+ user.getMemberPic();
						UrlImageViewHelper.setUrlDrawable(imageViewAvatar,
								imageUrl);
					}
				});
			}

			return uploadOk;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			mProgressDialog.dismiss();
			if (result) {
				showToast(getResources().getString(
						R.string.setting_edit_avatar_success));
			} else {
				showToast(getResources().getString(
						R.string.setting_edit_profile_fail));
			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog.show();
		}
	}
}